#include <iostream>
#include <pthread.h>
#include <cassert>
#include <cstring>
#include <unistd.h>
#include <vector>
using namespace std;


class ThreadData
{
public:
    pthread_t tid;
    int number;
    char namebuffer[128];
};

class ThreadReturn
{
public:
    int exit_code;
    int exit_result;
};

void* start_routine(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);//安全的强制转换类型
    int cnt = 0;
    while(1)
    {
        sleep(1);
        cout << "new thread create successfully : " << td->namebuffer << endl;
        cnt++;
        if(cnt == 10) pthread_exit(nullptr);
    }
    // while(1)
    // {
    //     cout << "我是新线程" << endl;
    //     sleep(1);
    // }
    // ThreadReturn* tr = new ThreadReturn;
    // tr->exit_code = 11;
    // tr->exit_result = 666;
    return (void*)td->number;
    // return tr;
    // pthread_exit(nullptr);
    // return nullptr;
}

int main()
{
    vector<ThreadData*> threads;
#define NUM 4
    for(int i = 0; i < NUM; i++)
    {   
        ThreadData* td = new ThreadData;
        td->number = i + 1;
        snprintf(td->namebuffer, sizeof(td->namebuffer), "%s:%d", "thread", i+1);
        int n = pthread_create(&td->tid, nullptr, start_routine, td);
        threads.push_back(td);
        sleep(1);
    }
    // for(auto& iter : threads)
    // {
    //     cout << "pthread create : " << iter->namebuffer << " : " << iter->tid << " success !" << endl;
    // }
    int cnt = 0;
    while(1)
    {
        cout << "main thread running...." << endl;
        cnt++;
        if(cnt == 8)
        {
            cout << "---------------------------" <<endl;
            cout << "some thread cancle" << endl;
            for(int i = 0; i < threads.size()/2; i++)
            {
                pthread_cancel(threads[i]->tid);
                cout << "pthread_cancel : " << threads[i]->namebuffer << " success" << endl;
            }

            for(auto& iter : threads)
            {
                void* ret = nullptr;
                int n = pthread_join(iter->tid, (void**)&ret);
                assert(n == 0);
                cout << "pthread join : " << iter->namebuffer << " success, exit_code : " << (long long)ret << endl;
                delete iter;
            }
            cout << "main quit" << endl;
            pthread_exit(nullptr);
        }
        sleep(1);
    }
    // pthread_t tid;
    // int n = pthread_create(&tid, nullptr, start_routine, (void*)"thread new");
    
    
    
    // while(1)
    // {
    //     cout << "我是主线程" << endl;
    //     sleep(1);
    // }
    return 0;
}